<?php

/**
 * $Id: handler_base.php 12 2010-11-28 20:02:53Z LEON $
 * $Author: LEON $
 * $LastChangedDate: 2010-11-28 20:02:53 +0000 (Sun, 28 Nov 2010) $
 * $Revision: 12 $
 */

namespace cmFly\controller\system\config;

use cmFly\controller\system\exceptions;
use cmFly\controller\system\config\instance;

abstract class handler_base {

    protected $dir;
    protected $parent;
    protected $loaded_configs;

    public function __construct($dir, handler_base $parent=NULL) {
	if (substr($dir, -1) != '/') {
	    $dir.='/';
	}
	if ($parent) {
	    $this->set_parent($parent);
	}
	$this->dir = $dir;
    }

    public function __get($config_name) {
	if ($this->loaded($config_name)) {
	    return $this->loaded_configs[$config_name];
	}
	if ($this->exists($config_name)) {
	    $arr = $this->load($config_name);
	    $this->loaded_configs[$config_name] = new instance($this, $config_name, $arr);
	    return $this->loaded_configs[$config_name];
	}
	$parent = $this->get_parent();
	if ($parent && $parent->$config_name) {
	    return $parent->$config_name;
	}
	throw new exceptions\fatal('Can\'t find "' . $config_name . '" config file!');
    }

    protected function loaded($config_name) {
	return isset($this->loaded_configs[$config_name]);
    }

    protected function set_parent(handler_base $parent) {
	$this->parent = $parent;
    }

    protected function get_parent() {
	return $this->parent;
    }

    public function exists($config_name) {
	return file_exists($this->dir . $config_name . $this->get_file_ext());
    }

    public function new_config($config_name) {
	return new instance($this, $config_name, Array());
    }

    public function get_dir() {
	return $this->dir;
    }

    abstract protected function get_file_ext();

    abstract protected function load($config_name);

    abstract public function save(instance $config);
}

?>